package com.logisticsinquiry.android.ui.trace

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.logisticsinquiry.android.R
import kotlinx.android.synthetic.main.trace.*
import org.w3c.dom.Text

class TraceFragment:Fragment() {
    val viewModel by lazy { ViewModelProvider(this).get(TraceViewModel::class.java) }
    private lateinit var adapter: TraceAdapter
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.trace, container, false)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        val layoutManager = LinearLayoutManager(activity)
        val intent = activity?.intent
        val logisticCode = intent?.getStringExtra("logisticCode")?:""
        val shipperName = intent?.getStringExtra("shipperName")?:""
        recycler_trace.layoutManager = layoutManager
        adapter = TraceAdapter(this, viewModel.traceList)
        recycler_trace.adapter = adapter
        val code: TextView = view!!.findViewById(R.id.LogisticCode)
        val name: TextView = view!!.findViewById(R.id.ShipperName)
        code.text = logisticCode
        name.text = shipperName
        viewModel.expressQuery(logisticCode)
        viewModel.expressQueryLiveData.observe(viewLifecycleOwner, Observer {
                result ->
            var traces = result.getOrNull()
            if(traces != null){
                traces = traces.reversed()
                recycler_trace.visibility = View.VISIBLE
                viewModel.traceList.clear()
                viewModel.traceList.addAll(traces)
                adapter.notifyDataSetChanged()
            } else {
                Toast.makeText(activity,"未能查询到快递物流", Toast.LENGTH_SHORT).show()
                result.exceptionOrNull()?.printStackTrace()
            }
        })
    }
}